/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package cocos2d.common.schedule;

import java.util.Enumeration;
import java.util.Hashtable;

/**
 *
 * @author KieuAnh
 */
public class CCBaseScheduler implements CCScheduler
{
    private static class CCScheduleTimer
    {
        long expected;
        long remain;

        public CCScheduleTimer(long expected) {
            this.expected = expected;
            this.remain = 0;
        }

        public long getExpected() {
            return expected;
        }

        public void setExpected(long expected) {
            this.expected = expected;
        }

        public long getRemain() {
            return remain;
        }

        public void setRemain(long remain) {
            this.remain = remain;
        }
    }
    
    private final Hashtable schedules = new Hashtable();
    
    public void schedule(CCSchedule schedule)
    {
        this.schedule(schedule, 0);
    }

    public void schedule(CCSchedule schedule, long time)
    {
        if (this.schedules.containsKey(schedule))
        {
            // update time
            CCScheduleTimer timer = (CCScheduleTimer) this.schedules.get(schedule);
            timer.setExpected(time);
        }
        else
        {
            this.schedules.put(schedule, new CCScheduleTimer(time));
        }
    }

    public void unschedule(CCSchedule schedule)
    {
        this.schedules.remove(schedule);
    }

    public void run(long dt)
    {
        Enumeration eSch = this.schedules.keys();
        
        while (eSch.hasMoreElements())
        {
            CCSchedule sch = (CCSchedule) eSch.nextElement();
            CCScheduleTimer timer = (CCScheduleTimer) this.schedules.get(sch);
            timer.remain += dt;
            
            if (timer.remain >= timer.expected)
            {
                sch.run(timer.remain);
                
                timer.remain = 0;
            }
        }
    }
    
    public static CCBaseScheduler instance()
    {
        return inst;
    }
    
    private static CCBaseScheduler inst = new CCBaseScheduler();
}
